<template>
    <div class="box">
        <div class="zhuce">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                <el-form-item label="姓名" prop="conName">
                    <p style="color:#ccc;line-height:20px;font-size:12px;margin-bottom:8px;padding-left:10px;">
                        姓名在3-10个字符内
                    </p>
                    <el-input v-model="ruleForm.conName" clearable></el-input>
                    
                </el-form-item>
                <el-form-item label="身份证" prop="conId">
                    <el-input v-model="ruleForm.conId" clearable @blur="getName(ruleForm.conId)"></el-input>
                    
                </el-form-item>
                <el-form-item label="性别" prop="conGender" >
                    <el-radio-group v-model="ruleForm.conGender" :disabled="true">
                        <el-radio :label="0">女</el-radio>
                        <el-radio :label="1">男</el-radio>
                
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="年龄" prop="conAge" >
                    <el-input v-model="ruleForm.conAge" placeholder="年龄" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="conPhone">
                    <el-input v-model="ruleForm.conPhone" clearable></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="verificationCode">
                    <el-input v-model="ruleForm.verificationCode" placeholder="请输入验证码">
                        <el-button slot="suffix" :disabled="disabled" @click="getCode">
                            <span class="Time">{{btnTxt}}</span>
                        </el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="电子邮箱" prop="conEmail">
                    <el-input v-model="ruleForm.conEmail" clearable></el-input>
                </el-form-item>
                <el-form-item label="账号密码" prop="conPassword">
                    <el-input type="password" v-model="ruleForm.conPassword" clearable></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPassword">
                    <el-input type="password" v-model="ruleForm.checkPassword" clearable></el-input>
                </el-form-item>
                <el-form-item label="参赛类别" prop="conClass">
                    
                    <el-link href="https://cqudemo1.oss-cn-hangzhou.aliyuncs.com/%E6%96%87%E5%AD%A6%E8%AF%84%E5%A5%96%E5%A4%A7%E8%B5%9B%E4%B8%BB%E9%A2%98.docx" style="color:#82cfff;line-height:20px;font-size:12px;margin-bottom:8px;padding-left:10px;">请仔细阅读类别要求后认真选择<i class="el-icon-view el-icon--right"></i> </el-link>
                    <el-select v-model="ruleForm.conClass" placeholder="类别">
                        <el-option v-for="cls in classes" :key="cls.classId" :label="cls.className" :value="cls.classId"></el-option>
                    </el-select>
                    
                </el-form-item>
                <el-form-item label="生日" prop="conBirth" >
                    <el-date-picker v-model="ruleForm.conBirth" type="date" :disabled="true" placeholder="选择日期"
                        format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="register">注册</el-button>
                    <el-button @click="returnForm">取消</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>
<script>
    export default {
        data() {
            
            var validatorPhone = function (rule, value, callback) {
                if (value === '') {
                    callback(new Error('手机号不能为空'))
                } else if (!/^1\d{10}$/.test(value)) {
                    callback(new Error('手机号格式错误'))
                } else {
                    callback()
                }
            };
            var checkEmail = (rule, value, callback) => {
                const regUser = /^([a-zA-Z0-9]+[-_]?)+@[a-zA-Z0-9]+\.[a-z]+$/
                if (regUser.test(value)) {
                    return callback()
                }
                callback(new Error('邮箱不能为空'))
            }
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'))
                } else {
                    if (this.ruleForm.checkPassword !== '') {
                        this.$refs.ruleForm.validateField('checkPassword')
                    }
                    callback()
                }
            }
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== this.ruleForm.conPassword) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
            var isCardId = (rule, value, callback) => {
                if (!value) {
                    return new Error("请输入身份证号)");
                } else {
                    const reg =
                        /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
                    const card = reg.test(value);
                    if (!card) {
                        callback(new Error("身份证号格式有误！"));
                    } else {
                        callback();
                    }
                }
            };
            return {
                btnTxt: "获取验证码",
                // 是否禁用  即点击之后一段时间内无法再点击
                disabled: false,
                time: 0,
                
                formLabelWidth: '120px',
                classes:[],
                ruleForm: {
                    conName: '',
                    conId: '',
                    conAge:'',
                    conGender:'',
                    conClass:'',
                    conPhone:'',
                    conEmail:'',
                    conBirth:'',
                    conPassword: '',
                    checkPassword: '',
                    verificationCode:'',
                },
                rules: {
                    conName: [
                    { required: true, message: "请输入姓名", trigger: "blur" },
                    { min: 2, max: 10, message: '长度在2-10个字符', trigger: "blur" }
                    ],
                    conPhone: [
                    { required: true, message: "请输入电话", trigger: "blur" },
                    { validator: validatorPhone, trigger: 'blur' }
                    ],
                    conId:[
                    { required: true, message: "请输入身份证", trigger: "blur" },
                    { validator: isCardId, trigger: 'blur' }
                    ],
                    conEmail: [
                    { required: true, message: "请输入邮箱", trigger: "blur" },
                    { validator: checkEmail, trigger: 'blur' }
                    ],
                    conPassword: [
                    { required: true, message: "请输入密码", trigger: "blur" },
                    { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPassword: [
                    { required: true, message: "请确认密码", trigger: "blur" },
                    { validator: validatePass2, trigger: 'blur' }
                    ],
                    conClass:[
                    { required: true, message: "请选择参赛类别", trigger: "blur" },
                    ],
                    verificationCode: [
                        { required: true, trigger: 'blur', message: '请输入4位验证码' },
                        { required: true, trigger: 'blur', min: 4, max: 6, message: '验证码错误' }
                    ],
                }
            }
        },
        methods: {
            //获取手机验证码方法
            getCode() {
                // 校验手机号码
                if (!this.ruleForm.conPhone) {
                    //号码校验不通过
                    this.$message({
                        message: '请输入手机号',
                        type: 'warning',
                    });
                    //正则判断 从1开始，第二位是35789中的任意一位，以9数字结尾
                } else if (!/1[35789]\d{9}/.test(this.ruleForm.conPhone)) {
                    // 失去焦点后自动触发校验手机号规则
                } else {
                    this.time = 60;
                    this.disabled = true;
                    //调用倒计时方法
                    this.timer();
                    // 封装的axios接口
                    this.$axios({
                        method: 'post',
                        url: 'http://localhost:8080/RegistersendMsg',
                        data: {
                            phone: this.ruleForm.conPhone
                        },
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }).then(res => {
                        if (res.data.code) {
                            this.$message({
                                type: "success",
                                message: '验证码已发送'
                            })
                        } else {
                            
                            this.$message({
                                type: "error",
                                message: '验证码发送失败'
                            })
                            

                        }
                    })
                }
            },
            // 倒计时方法
            timer() {
                if (this.time > 0) {
                    this.time--;
                    // console.log(this.time);
                    this.btnTxt = this.time + "s后重新获取验证码";
                    setTimeout(this.timer, 1000);
                } else {
                    this.time = 0;
                    this.btnTxt = "获取验证码";
                    this.disabled = false;
                }
            },
            returnForm() {
                // 返回login界面
                this.$router.push('/login')
            },
            
            async fetchData(){
                this.$axios({
                    method: 'get',
                    url: 'http://localhost:8080/class',
                }).then(res => {
                    if (res.data.code == 1) {
                        this.classes = res.data.data;

                    }

                })
            },
            getName(iden) {
                let val = iden.length;
                let sex = null;
                let myDate = new Date();
                let month = myDate.getMonth() + 1;
                let day = myDate.getDate();
                let age = 0;
                let birth = null;
                let password = null;
                if (val === 18) {
                    age = myDate.getFullYear() - iden.substring(6, 10) - 1;
                    sex = iden.substring(16, 17);
                    birth = iden.substring(6, 10) + "-" + iden.substring(10, 12) + "-" + iden.substring(12, 14);
                    if (iden.substring(10, 12) < month || iden.substring(10, 12) == month && iden.substring(12, 14) <= day) age++;
                    password = iden.substring(12, 18);
                }
                if (val === 15) {
                    age = myDate.getFullYear() - iden.substring(6, 8) - 1901;
                    sex = iden.substring(13, 14);
                    password = iden.substring(9, 15);
                    birth = "19" + iden.substring(6, 8) + "-" + iden.substring(8, 10) + "-" + iden.substring(10, 12);
                    if (iden.substring(8, 10) < month || iden.substring(8, 10) == month && iden.substring(10, 12) <= day) age++;
                }

                if (sex % 2 === 0)
                    sex = 0
                else
                    sex = 1
                this.ruleForm.conGender = sex;
                this.ruleForm.conAge = age;
                this.ruleForm.conBirth = birth;
                this.ruleForm.conPassword = password;

            },
            register() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        console.log(this.ruleForm)
                        var data = {
                            postData: {
                                conIndex: '',
                                conId: this.ruleForm.conId,
                                conName: this.ruleForm.conName,
                                conAge: this.ruleForm.conAge,
                                conGender: this.ruleForm.conGender,
                                conEmail: this.ruleForm.conEmail,
                                conPassword: this.ruleForm.conPassword,
                                conPhone: this.ruleForm.conPhone,
                                conClass: this.ruleForm.conClass,
                                conBirth: this.ruleForm.conBirth,
                                conCreatetime: '',
                                conUpdatetime: '',
                            },
                            verificationCode: this.ruleForm.verificationCode
                        }
                        
                        
                        this.$axios({
                            method: 'post',
                            url: 'http://localhost:8080/register',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            data: JSON.stringify(data)
                            
                        }).then(
                            (response) => {
                                console.log(response.data);
                                if (response.data.code == 1) {
                                    alert('注册成功！返回登录页面！')
                                    this.$router.push('/login')
                                }
                                if (response.data.msg === 'SAME_CONID') {
                                    this.$message({
                                        type: 'error',
                                        message: "该身份证已注册！"
                                    });
                                }
                                if(response.data.msg ==='验证码错误'){
                                    this.$message({
                                        type: 'error',
                                        message: "验证码错误!"
                                    });
                                }

                            },
                            (response) => {
                                console.log(response)
                                alert('出问题啦！！！')
                            }
                        )
                    }
                })
                
            }
        },
        mounted(){
           this.fetchData();
        }
    }
</script>
<style lang="less" scoped>
    .box {
        height: 100%;
        background-color: #2e4e6e;
    }

    .zhuce {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 450px;
        height: 450px;
        background-color: #fff;
        border-radius: 3px;
    }

    .el-form-item {
        margin-top: 30px;
        width: 400px;
    }
</style>